package blog

import (
	"fmt"
	kcommon "longblog/framework/tools/common"
	kinit "longblog/work/base/initialize"

	jgorm "github.com/jinzhu/gorm"
)

var ObjArticleType ArticleType

type ArticleType struct {
	ID        int64  `gorm:"primary_key" json:"-"`
	LangType  int64  `gorm:"column:lang_type" json:"lang_type"`
	TypeName  string `gorm:"column:type_name" json:"type_name"`
	Status    int64  `gorm:"column:status" json:"status"`
	SortNum   int64  `gorm:"column:sort_num" json:"sort_num"`
	CreatedAt string `gorm:"column:created_at" json:"created_at"`
	UpdatedAt string `gorm:"column:updated_at" json:"updated_at"`
}

func (ArticleType) TableName() string {
	return "article_type"
}

func (ts *ArticleType) Insert(tx *jgorm.DB, lang_type int64, type_name string) (ArticleType, error) {
	if tx == nil {
		tx = kinit.Gorm
	}

	tm := kcommon.TimestampToDateTime(kcommon.GetTimes())
	obj := ArticleType{
		LangType:  lang_type,
		TypeName:  type_name,
		Status:    1,
		SortNum:   0,
		CreatedAt: tm,
		UpdatedAt: tm,
	}
	if err := tx.Create(&obj).Error; err != nil {
		kinit.LogError.Println(err)
		return obj, err
	}
	return obj, nil
}

func (ts *ArticleType) GetById(tx *jgorm.DB, id int64) (result ArticleType, err error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	err = tx.Where("id = ?", id).First(&result).Error
	return
}
func (ts *ArticleType) GetByIds(tx *jgorm.DB, ids []int64) (result []*ArticleType, err error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	err = tx.Where("id IN (?)", ids).Find(&result).Error
	return
}
func (ts *ArticleType) UpdateMById(tx *jgorm.DB, id int64, m map[string]interface{}) (err error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	err = tx.Model(&ArticleType{}).Where("id=?", id).Updates(m).Error
	return
}
func (ts *ArticleType) DeleteById(tx *jgorm.DB, id int64) (err error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	var obj ArticleType
	err = tx.Where("id = ?", id).Delete(&obj).Error
	return
}
func (ts *ArticleType) GetAllWithTitleOrLangType(tx *jgorm.DB, typeName string, langType int64) (result []ArticleType, err error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	if len(typeName) > 0 {
		tx = tx.Where("type_name LIKE ?", fmt.Sprintf("%s%s%s", "%", typeName, "%"))
	}
	if langType > 0 {
		tx = tx.Where("lang_type = ?", langType)
	}
	err = tx.Where("status = ?", 1).Order("sort_num desc").Find(&result).Error
	return
}

func (ts *ArticleType) GetAll(tx *jgorm.DB) (result []ArticleType, err error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	err = tx.Where("status = ?", 1).Order("sort_num desc").Find(&result).Error
	return
}
